#include "GUIError.h"
#include <stdio.h>
#include <stdarg.h>
#include "GUIBase.h"

namespace YGUI
{
    namespace __ErrorGlobalVar
    {
        static unsigned long __LastErrorCode = ERRORCODE::GUI_ERROR_SUCCESS;
        static String __LastErrorMsg;
        static const int __DefaultErrMsgStrSize = 128;
    };

    unsigned long Err::getLastError(void)
    {
        return __ErrorGlobalVar::__LastErrorCode;
    }

    void Err::setLastError(unsigned long nErrorCode)
    {
        __ErrorGlobalVar::__LastErrorCode = nErrorCode;
    }

    const String& Err::getLastErrMsg(void)
    {
        return __ErrorGlobalVar::__LastErrorMsg;
    }

    void Err::setLastErrMsg(const String& strErrMsg)
    {
        __ErrorGlobalVar::__LastErrorMsg = strErrMsg;
    }

    void Err::setLastErrFormatMsg(const char* fmt, ...)
    {
        if(fmt == NULL)
            return;
        va_list args;
        va_start(args, fmt);
        int size = _vscprintf(fmt, args) + 1;

        if(size <= __ErrorGlobalVar::__DefaultErrMsgStrSize)
        {
            char buffer[__ErrorGlobalVar::__DefaultErrMsgStrSize] = { 0 };
            vsprintf_s(buffer, __ErrorGlobalVar::__DefaultErrMsgStrSize, fmt, args);
            __ErrorGlobalVar::__LastErrorMsg.assign(buffer);
        }
        else
        {
            char* buffer = MEMCHECK_NEW char[size];
            vsprintf_s(buffer, size, fmt, args);
            __ErrorGlobalVar::__LastErrorMsg.assign(buffer);
            delete [] buffer;
        }
    }
};